import { createRouter, createWebHistory } from "vue-router";
import { start, close } from "@/utils/nprogressUtils"
import { useHomeStore } from '@/stores/index'
import { findTreeMenu, } from '@/apis/index'
import { getUserInfo } from "@/utils";

const routes = [
    {
        path: "/",
        name: "layout",
        redirect: "/login",
        component: () => import("@/views/Index.vue"),
        children: [
            {
                path: "index",
                name: "index",
                component: () => import("@/views/index/Index.vue")
            }
        ]
    },
    {
        path: "/login",
        name: "login",
        component: () => import("@/views/Login.vue") // 动态导入组件
    }
]; // 路由匹配规则
const history = createWebHistory(); // 路由模式
const router = createRouter({
    history,
    routes,
}) // 创建路由实例

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
    // debugger
    start() // 开启进度条
    const store = useHomeStore()
    if (to.path === '/login' && !store.isLogin) {
        next()
        return
    }
    if ((store.isLogin && store.menuTree.length <= 0)) {
        store.menuTree = await findTreeMenu(getUserInfo(localStorage.getItem('token')))
        store.addRouters() // 动态添加路由
        next({ ...to, replace: true }) // 重定向到当前路由，避免刷新页面后，路由丢失
        return
    }
    next()
})

router.afterEach(() => {
    close() // 关闭进度条
})

export default router; // 导出路由实例

